<?php
/**
 * 低价团相关
 *
 * @author 周剑锋 <camfee@foxmai.com>
 */

namespace controls\MobileApi\Center;

use Center\Category;
use Center\Active;
use Center\CoinLog;
use Center\CouponConfig;
use Center\QrCode;
use Center\Shop;
use Center\UserCoupon;
use Center\UserShop;
use Center\VoteActive;
use Center\VoteActiveInfo;
use Center\VoteActiveShop;
use MobileApi\ApiBase;
use Center\User;
use Notice\Sys;

/**
 * 低价团相关
 *
 * @package Center
 * @author  周剑锋 <camfee@foxmai.com>
 * @since   1.0.0 2017-01-03
 */
class Group extends ApiBase
{

    /**
     * 低价团首页
     *
     * <pre>
     * GET
     *     无传入参数
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "RedDot": 1, // 是否有新消息 1：是 0：否
     *         "IsShop": 1, // 是否是商家 1：是 0：否
     *         "CateList": [
     *             {
     *                 "CatId": 1,  // 分类id
     *                 "CatName": "电器", // 分类名称
     *                 "CatIcon": "分类icon图地址" // 分类icon地址
     *             },...
     *         ]
     *     },
     *     "ServerTime": 1511181246
     * }
     * 异常状态：
     * </pre>
     */
    public function getIndex()
    {
        $uid = $this->isLogin(false);
        $user_info = User::getInfoByIds($uid);
        $list = Category::getAllCate();
        $cate_list = [];
        if (!empty($list['data'])) {
            foreach ($list['data'] as $v) {
                $cate_list[] = [
                    'CatId' => $v['Id'],
                    'CatName' => $v['Name'],
                    'CatIcon' => str_replace('.jpg', '_100.jpg', $v['IconUrl']),
                ];
            }
        }
        //红点
        $reddot = 0;
        if ($uid > 0) {
            $rednum = Sys::getNum($uid);
            $reddot = $rednum[Sys::REDIS_NUM_FIELD_GROUP_MSG] > 0 ? 1 : 0;
        }

        $data = [
            'RedDot' => $reddot,
            'IsShop' => (int)$user_info['IsShop'],
            'CateList' => $cate_list,
        ];

        $this->output(200, $data);
    }

    /**
     * 获取分类下店铺列表
     *
     * <pre>
     * GET
     *     cityid: 可选， 城市id 默认为醴陵
     *     catid:  必选， 分类id
     *     offset: 可选， 偏移量 默认0
     *     limit:  可选， 每次数量, 最高不超过50 默认20
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "CatId": 1, // 分类id
     *         "CatName": "电器", // 分类名称
     *         "Total": 21, // 店铺总数
     *         "List": [
     *             {
     *                 "ShopId": 1, // 店铺id
     *                 "ShopName": "电器店铺", // 店铺名称
     *                 "ShopCover": "图店铺封面图地址" // 店铺封面图地址
     *             },...
     *         ]
     *     },
     *     "ServerTime": 1511183301
     * }
     * 异常状态：
     * 201：参数错误
     * </pre>
     */
    public function getShopList()
    {
        //$uid = $this->isLogin(false);
        $catid = intval($_GET['catid']);
        //        $user_info = User::getInfoByIds($uid);
        //        $city_id = (int)$user_info['CityId'];
        $city_id = intval($_GET['cityid']) > 0 ? intval($_GET['cityid']) : 1;
        $offset = (int)$_GET['offset'];
        $limit = (int)$_GET['limit'];
        $offset = max(0, $offset);
        $limit = $limit < 1 ? 20 : min($limit, 50);
        $cate = Category::getInfoByIds($catid);
        if (empty($cate)) {
            $this->output(201, '参数错误');
        }

        $list = Shop::getListByCityCatId($city_id, $catid, $offset, $limit);

        $data = [
            'CatId' => $catid,
            'CatName' => (string)$cate['Name'],
            'Total' => (int)$list['count'],
            'List' => []
        ];
        if (!empty($list['data'])) {
            foreach ($list['data'] as $v) {
                $data['List'][] = [
                    'ShopId' => $v['Id'],
                    'ShopName' => $v['Name'],
                    'ShopCover' => $v['Cover'],
                ];
            }
        }

        $this->output(200, $data);
    }

    /**
     * 店铺详情
     *
     * <pre>
     * GET
     *     shopid: 必选， 店铺id
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "ShopId": 1, // 店铺id
     *         "ShopName": "店铺名称", // 店铺名称
     *         "ShopDesc": "店铺描述标题", // 店铺描述标题
     *         "MemberNum": 233, // 会员数
     *         "IsDiscount": 1, // 是否可以领取优惠 1：是 0：否
     *         "ShopAddress": "店铺地址",
     *         "ShopMobile": "店铺联系电话",
     *         "ShopQrCodeUrl": "店铺二维码地址",
     *         "ShopQrCodeId": "店铺二维码id",
     *         "ContentList": [ // 内容数组
     *             {
     *                 "Text": "电器",
     *                 "ImgUrl": "图店铺封面图地址"
     *             },...
     *         ]
     *     },
     *     "ServerTime": 1511184252
     * }
     * 异常状态：
     * </pre>
     */
    public function getShopInfo()
    {
        $uid = $this->isLogin(false);
        $shopid = intval($_GET['shopid']);
        $shop = Shop::getInfoByIds($shopid);
        if (empty($shop)) {
            $this->output(200, '参数错误');
        }
        //取用户的优惠券
        $isdiscount = 1;
        if ($uid > 0) {
            $coupon = UserShop::getUserShopList($uid, $shopid, UserCoupon::COUPON_VALID);
            if ($coupon['count'] > 0) {
                $isdiscount = 0;
            }
        }
        $active = Active::getLastActive($shopid);
        $qr_code = QrCode::checkUserTypeCode($uid, QrCode::TYPE_SHOP_CHAP, $shopid);
        $code_url = '';
        $code_id = 0;
        if (!empty($qr_code)) {
            $code_id = $qr_code['Id'];
            $code_url = 'gold://app/vip?id=' . $code_id;
        }
        $cont = unserialize($shop['Content']);
        $content = [];
        if (count($cont) > 0) {
            foreach ($cont as $k => $v) {
                $content[] = [
                    'Text' => $v['Text'],
                    'ImgUrl' => $v['ImgUrl'],
                ];
            }
        }

        $data = [
            'ShopId' => $shopid,
//            'ActiveId' => (int)$active['Id'],
            'ActiveId' => (int)$active['Id'] > 0 ? (int)$active['Id'] : $shop['ActiveId'],
            'ShopName' => $shop['Name'],
            'ShopDesc' => $shop['Description'],
            'MemberNum' => $shop['Members'] + $shop['Brower'],
            'IsDiscount' => $isdiscount,
            'ShopAddress' => $shop['Address'],
            'ShopMobile' => $shop['Mobile'],
            'ShopQrCodeUrl' => $code_url,
            'ShopQrCodeId' => $code_id,
            'ContentList' => $content
        ];
        Shop::update($shopid, ['Brower' => ['Brower', '+1']]);
        $this->output(200, $data);
    }

    /**
     * 领店铺优惠
     *
     * <pre>
     * POST
     *     shopid: 必选， 店铺id
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "ShopId": 1,
     *         "ShopName": "店铺名称",
     *         "MemberNum": 233, // 会员数
     *         "ShopAddress": "店铺地址",
     *         "ShopMobile": "店铺联系电话",
     *         "ShopQrCodeUrl": "店铺二维码地址",
     *         "ShopQrCodeId": "店铺二维码Id"
     *     },
     *     "ServerTime": 1511184462
     * }
     * 异常状态：
     * 201：已获得过此优惠券
     * </pre>
     */
    public function getShopDiscount()
    {
        $shopid = intval($_POST['shopid']);
        $uid = $this->isLogin(true);

        $couponinfo = UserShop::getUserShopList($uid, $shopid, UserCoupon::COUPON_VALID);
        if ($couponinfo['count'] > 0) {
            $this->output(201, '已获得过此优惠券且未使用');
        }
        $info = [
            'UserId' => $uid,
            'ShopId' => $shopid,
            'Status' => UserCoupon::STATUS_UN_USED,
            'StartTime' => date('Y-m-d H:i:s'),
            'EndTime' => date('Y-m-d H:i:s', strtotime('+3 day')),
        ];
        $id = UserCoupon::add($info);
        if ($id !== false) {
            $shopinfo = Shop::getInfoByIds($shopid);
            $code_info = QrCode::checkUserTypeCode($uid, QrCode::TYPE_SHOP_CHAP, $shopid);
            if (empty($code_info)) {
                //会员+1
                Shop::update($shopid, ['Members' => ['Members', '+1']]);
                $code_id = QrCode::addQrCode($shopid, $uid);
            } else {
                $code_id = $code_info['Id'];
            }

            $data = [
                'ShopId' => $shopid,
                'ShopName' => $shopinfo['Name'],
                'MemberNum' => $shopinfo['Members'] + $shopinfo['Brower'],
                'ShopAddress' => $shopinfo['Address'],
                'ShopMobile' => $shopinfo['Mobile'],
                'ShopQrCodeUrl' => 'gold://app/vip?id=' . $code_id,
                'ShopQrCodeId' => $code_id,
            ];

            $this->output(200, $data);
        } else {
            $this->output(203, '网络繁忙，请稍后再试！');
        }
    }

    /**
     * 名优品牌榜分类
     *
     * <pre>
     * GET
     *     无传入参数
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "CateList": [
     *             {
     *                 "CatId": 1,  // 分类id
     *                 "CatName": "电器", // 分类名称
     *                 "CatIcon": "分类icon图地址" // 分类icon地址
     *             },...
     *         ]
     *     },
     *     "ServerTime": 1511183301
     * }
     * 异常状态：
     * </pre>
     */
    public function getBrandRankCate()
    {
        $list = Category::getAllCate();
        $data['CateList'] = [];
        if (!empty($list['data'])) {
            foreach ($list['data'] as $v) {
                $data['CateList'][] = [
                    'CatId' => $v['Id'],
                    'CatName' => $v['Name'],
                    'CatIcon' => $v['IconUrl'],
                ];
            }
        }

        $this->output(200, $data);
    }

    /**
     * 名优品牌榜详情
     *
     * <pre>
     * GET
     *     catid:  必选， 分类id
     *     city:   必选， 城市名称
     *     offset: 可选， 偏移量 默认0
     *     limit:  可选， 每次数量, 最高不超过50 默认20
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "CatId": 1, // 分类id
     *         "CatName": "电器", // 分类名称
     *         "Total": 21, // 店铺总数
     *         "List": [
     *             {
     *                 "ShopId": 1, // 店铺id
     *                 "ShopName": "电器店铺", // 店铺名称
     *                 "ShopCover": "图店铺封面图地址" // 店铺封面图地址
     *             },...
     *         ]
     *     },
     *     "ServerTime": 1511183301
     * }
     * 异常状态：
     * 201:参数错误
     * </pre>
     */
    public function getBrandRank()
    {
        $uid = $this->isLogin(false);
        $catid = intval($_GET['catid']);
        $user_info = User::getInfoByIds($uid);
        $city_id = (int)$user_info['CityId'];
        $offset = (int)$_GET['offset'];
        $limit = (int)$_GET['limit'];
        $offset = max(0, $offset);
        $limit = $limit < 1 ? 20 : min($limit, 50);
        $cate = Category::getInfoByIds($catid);
        if (empty($cate)) {
            $this->output(201, '参数错误');
        }

        $list = Shop::getListByCityCatId($city_id, $catid, $offset, $limit);
        $data = [
            'CatId' => $catid,
            'CatName' => (string)$cate['Name'],
            'Total' => (int)$list['count'],
            'List' => []
        ];
        if (!empty($list['data'])) {
            foreach ($list['data'] as $v) {
                $data['List'][] = [
                    'ShopId' => $v['Id'],
                    'ShopName' => $v['Name'],
                    'ShopCover' => $v['Cover'],
                ];
            }
        }

        $this->output(200, $data);
    }

    /**
     * 最受消费者欢迎榜
     *
     * <pre>
     * GET
     *     offset: 可选， 偏移量 默认0
     *     limit:  可选， 每次数量, 最高不超过50 默认20
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "Type": 1, // 类型 1：投票 2:领奖
     *         "RuleText":'http://m.jinguonet.com/app/help/rule2.php', // 规则文案H5
     *         "Total": 21, // 店铺总数
     *         "List": [
     *             {
     *                 "ShopId": 1, // 店铺id
     *                 "ShopName": "电器店铺", // 店铺名称
     *                 "ShopCover": "图店铺封面图地址", // 店铺封面图地址
     *                 "Rank": 1, // 店铺封排名
     *                 "VoteNum": 555 // 店铺得票数
     *             },...
     *         ]
     *     },
     *     "ServerTime": 1511183301
     * }
     * 异常状态：
     * 201：没有有效的活动
     * </pre>
     */
    public function getGreetRank()
    {
        $offset = (int)$_GET['offset'];
        $limit = (int)$_GET['limit'];
        $offset = max(0, $offset);
        $limit = $limit < 1 ? 20 : min($limit, 50);
        $vote_active = VoteActive::getLastValidActive();
        if (empty($vote_active)) {
            $this->output(201, '没有有效的活动');
        }

        $list_info = VoteActiveShop::getVoteShop($vote_active['Id'], $offset, $limit);
        $list = [];
        if (!empty($list_info['data'])) {
            $ids = [];
            foreach ($list_info['data'] as $v) {
                $ids[] = $v['ShopId'];
            }
            $shops = Shop::getInfoByIds($ids);
            $rank = VoteActiveShop::getVoteRank();
            foreach ($list_info['data'] as $v) {
                $id = $v['ShopId'];
                $list[] = [
                    'ShopId' => $id,
                    'ShopName' => $shops[$id]['Name'],
                    'ShopCover' => $shops[$id]['Cover'],
                    'Rank' => $rank[$v['Id']],
                    'VoteNum' => $v['VoteNum'],
                ];
            }
        }
        $data = [
            'Type' => $vote_active['Status'],
//            'RuleText' => $vote_active['Description'],
            'RuleText' => 'http://m.jinguonet.com/app/help/rule2.php',
            'Total' => (int)$list_info['count'],
            'List' => $list
        ];
        $this->output(200, $data);
    }

    /**
     * 投票
     *
     * <pre>
     * POST
     *     shopid: 必选， 商铺id
     *     num:    必选， 投票数 1-100
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {},
     *     "ServerTime": 1511183301
     * }
     * 异常状态：
     * 201:参数错误
     * 202：金果不足
     * 203：投票活动不存在
     * </pre>
     */
    public function vote()
    {
        $uid = $this->isLogin(true);
        $vote_active = VoteActive::getLastValidActive();
        if (empty($vote_active)) {
            $this->output(203, '投票活动不存在');
        }
        $shopid = (int)$_POST['shopid'];
        $num = (int)$_POST['num'];
        if ($shopid < 1 || $num < 1 || $num > 100) {
            $this->output(201, '参数错误');
        }
        $user_info = User::getInfoByIds($uid);
        if ($num > $user_info['JCoin']) {
            $this->output(202, '金果不足');
        }

        //$res = User::updateJCoin($uid, -$num);
        $res = CoinLog::addCoinLog($uid, -$num, CoinLog::TYPE_VOTE);
        if ($res === false) {
            $this->output(204, '金果扣除失败');
        }
        $data = [
            'ActiveId' => $vote_active['Id'],
            'ShopId' => $shopid,
            'UserId' => $uid,
            'VoteNum' => $num,
        ];
        $res = VoteActiveInfo::checkVote($data['ActiveId'], $shopid, $uid);
        if (empty($res)) {
            $ret = VoteActiveInfo::add($data);
        } else {
            $ret = VoteActiveInfo::update($res['Id'], ['VoteNum' => ['VoteNum', '+' . $num]]);
        }

        if ($ret === false) {
            $this->output(204, '投票失败');
        } else {
            $active_shop = VoteActiveShop::checkShop($vote_active['Id'], $shopid);
            VoteActiveShop::update($active_shop['Id'], ['VoteNum' => ['VoteNum', '+' . $num]]);
        }

        $this->output();
    }

    /**
     * 领奖
     *
     * <pre>
     * POST
     *     shopid: 必选， 商铺id
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {},
     *     "ServerTime": 1511183301
     * }
     * 异常状态：
     * 201:此活动暂时不能领奖
     * 202：你已经领取过该奖品
     * 203：只有帮它投票的才有机会领取哦
     * </pre>
     */
    public function getReward()
    {
        $uid = $this->isLogin(true);
        $vote_active = VoteActive::getLastValidActive();
        if (empty($vote_active)) {
            $this->output(204, '投票活动不存在');
        }
        $shopid = (int)$_POST['shopid'];
        if ($shopid == 0) {
            $shopid = (int)$_POST['shopId'];
        }
        $check = VoteActiveInfo::checkVote($vote_active['Id'], $shopid, $uid);
        if (empty($check)) {
            $this->output(203, '只有帮它投票的才有机会领取哦');
        }
        if ($check['VoteNum'] <= $check['RewardNum']) {
            $this->output(202, '你已经领取过该奖品');
        }
        if ($check['RewardStatus'] != 1) {
            $this->output(201, '您投票的商家没有中奖');
        }

        $coupon_list = CouponConfig::getList(['ShopId' => $shopid]);
        $coupon = current($coupon_list['data']);
        if ($coupon['Stock'] < 1) {
            $this->output(206, '商家优惠券已领取完');
        }
        $res = VoteActiveInfo::update($check['Id'], ['RewardNum' => ['RewardNum', '+1']]);
        if ($res === false) {
            $this->output(205, '数据更新错误');
        }
        $info = [
            'UserId' => $uid,
            'CouponId' => $coupon['Id'],
            'ShopId' => $shopid,
            'Amount' => 1,
            //            'Type' => $coupon['Type'],
            'Status' => UserCoupon::STATUS_UN_USED,
            'StartTime' => $coupon['StartTime'],
            'EndTime' => $coupon['EndTime'],
            'UpdateTime' => $coupon['EndTime'], // 有效截止日期或者使用时间
        ];
        $id = UserCoupon::add($info);
        if ($id !== false) {
            //库存-1
            CouponConfig::update($coupon['Id'], ['Stock' => ['Stock', '-1']]);

            $this->output(200);
        } else {
            $this->output(203, '网络繁忙，请稍后再试！');
        }
    }

    /**
     * 用户金果榜
     *
     * <pre>
     * GET
     *     type:   可选， 排行时间类型 1：当月 2：当季 3：当年 默认1
     *     offset: 可选， 偏移量 默认0
     *     limit:  可选， 每次数量, 最高不超过100 默认100
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "Type": 1, // 时间类型 1：当月 2：当季 3：当年
     *         "RuleText":'http://m.jinguonet.com/app/help/rule.php', // 规则文案
     *         "Total": 21, // 总数
     *         "List": [
     *             {
     *                 "UserId": 1, // 店铺id
     *                 "UserNick": "用户昵称", // 用户昵称
     *                 "HeadUrl": "头像地址", // 头像地址
     *                 "Rank": 1, // 店铺封排名
     *                 "JCoinNum": 555 // 金果数
     *             },...
     *         ]
     *     },
     *     "ServerTime": 1511183301
     * }
     * 异常状态：
     * </pre>
     */
    public function getJinGuoRank()
    {
        $type = (int)$_GET['type'];
        $offset = (int)$_GET['offset'];
        $limit = (int)$_GET['limit'];
        $offset = max(0, $offset);
        $limit = $limit < 1 ? 100 : min($limit, 100);
        $list = CoinLog::getRankList($type, $limit);
        $data = [
            'Type' => $type,
//            'RuleText' => '每月、每季、每年前三名的用户我们将会发送消息给您，您可以凭领奖二维码领取醴陵市金果网络技术有限公司提供的精美奖品。',
            'RuleText' => 'http://m.jinguonet.com/app/help/rule.php',
            'Total' => count($list),
            'List' => $list
        ];
        $this->output(200, $data);
    }

    /**
     * 搜索结果
     *
     * <pre>
     * GET
     *     str:    必选， 搜索关键字
     *     offset: 可选， 偏移量 默认0
     *     limit:  可选， 每次数量, 最高不超过50 默认20
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "Total": 21, // 总数
     *         "List": [
     *             {
     *                 "ShopId": 1, // 店铺id
     *                 "ShopName": "电器店铺", // 店铺名称
     *                 "Keyword": "店铺关键字", // 店铺关键字
     *             },...
     *         ]
     *     },
     *     "ServerTime": 1511183301
     * }
     * 异常状态：
     * </pre>
     */
    public function getSearchList()
    {
        $str = trim($_GET['str']);
        $offset = (int)$_GET['offset'];
        $limit = (int)$_GET['limit'];
        $offset = max(0, $offset);
        $limit = $limit < 1 ? 20 : min($limit, 50);
        $list_info = Shop::searchShop($str, $offset, $limit);
        $list = [];
        if (!empty($list_info['data'])) {
            $shops = Shop::getInfoByIds($list_info['data']);
            foreach ($shops as $v) {
                $list[] = [
                    'ShopId' => $v['Id'],
                    'ShopName' => $v['Name'],
                    'Keyword' => $v['Keywords'],
                ];
            }
        }
        $data = [
            'Total' => (int)$list_info['count'],
            'List' => $list
        ];
        $this->output(200, $data);
    }

    /**
     * 获取全部分类
     *
     * <pre>
     * GET
     *     无传入参数
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "CateList": [
     *             {
     *                 "CatId": 1,  // 分类id
     *                 "CatName": "电器", // 分类名称
     *                 "CatIcon": "分类icon图地址" // 分类icon地址
     *             },...
     *         ]
     *     },
     *     "ServerTime": 1511181246
     * }
     * 异常状态：
     * </pre>
     */
    public function getAllCateList()
    {
        $list = Category::getAllCate();
//        $list = loadconf('shop/cate');
        $data['CateList'] = [];
        if (!empty($list)) {
            foreach ($list as $v) {
                $data['CateList'][] = [
                    'CatId' => $v['Id'],
                    'CatName' => $v['Name'],
                    'CatIcon' => $v['IconUrl'],
                ];
            }
        }

        $this->output(200, $data);
    }

}